import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useToolStore = defineStore('tool', () => {
  // 当前工具
  const currentTool = ref('select')
  
  // 工具配置
  const toolConfig = ref({
    select: {
      name: '选择工具',
      icon: 'cursor',
      shortcut: 'V',
      cursor: 'default'
    },
    wall: {
      name: '墙体工具',
      icon: 'wall',
      shortcut: 'W',
      cursor: 'crosshair',
      thickness: 20,
      color: '#374151'
    },
    furniture: {
      name: '家具工具',
      icon: 'sofa',
      shortcut: 'F',
      cursor: 'crosshair',
      defaultSize: { width: 100, height: 100 }
    },
    door: {
      name: '门工具',
      icon: 'door',
      shortcut: 'D',
      cursor: 'crosshair',
      width: 80,
      height: 200
    },
    window: {
      name: '窗户工具',
      icon: 'window',
      shortcut: 'N',
      cursor: 'crosshair',
      width: 120,
      height: 120
    },
    text: {
      name: '文字工具',
      icon: 'text',
      shortcut: 'T',
      cursor: 'text',
      fontSize: 16,
      fontFamily: 'Arial',
      color: '#000000'
    },
    measure: {
      name: '测量工具',
      icon: 'ruler',
      shortcut: 'M',
      cursor: 'crosshair',
      unit: 'cm',
      precision: 1
    },
    circuit: {
      name: '电路工具',
      icon: 'lightning',
      shortcut: 'C',
      cursor: 'crosshair',
      voltage: 220,
      current: 10
    },
    annotation: {
      name: '标注工具',
      icon: 'comment',
      shortcut: 'A',
      cursor: 'crosshair',
      color: '#FF6B6B',
      fontSize: 12
    }
  })

  // 工具状态
  const toolState = ref({
    isDrawing: false,
    drawingPoints: [],
    previewObject: null,
    snapPoints: [],
    guides: []
  })

  // 工具历史
  const toolHistory = ref([])

  // 计算属性
  const currentToolConfig = computed(() => toolConfig.value[currentTool.value])
  const currentToolName = computed(() => currentToolConfig.value?.name || '未知工具')
  const currentToolIcon = computed(() => currentToolConfig.value?.icon || 'question')
  const currentToolCursor = computed(() => currentToolConfig.value?.cursor || 'default')
  const isDrawingTool = computed(() => ['wall', 'furniture', 'door', 'window', 'text', 'circuit', 'annotation'].includes(currentTool.value))
  const isSelectionTool = computed(() => currentTool.value === 'select')
  const isMeasurementTool = computed(() => currentTool.value === 'measure')

  // Actions
  const setTool = (toolName) => {
    if (toolConfig.value[toolName]) {
      currentTool.value = toolName
      resetToolState()
    }
  }

  const getTool = () => currentTool.value

  const getToolConfig = (toolName) => {
    return toolConfig.value[toolName] || null
  }

  const updateToolConfig = (toolName, config) => {
    if (toolConfig.value[toolName]) {
      toolConfig.value[toolName] = { ...toolConfig.value[toolName], ...config }
    }
  }

  const resetToolState = () => {
    toolState.value = {
      isDrawing: false,
      drawingPoints: [],
      previewObject: null,
      snapPoints: [],
      guides: []
    }
  }

  const startDrawing = (point) => {
    if (isDrawingTool.value) {
      toolState.value.isDrawing = true
      toolState.value.drawingPoints = [point]
    }
  }

  const addDrawingPoint = (point) => {
    if (toolState.value.isDrawing) {
      toolState.value.drawingPoints.push(point)
    }
  }

  const updateDrawingPreview = (point) => {
    if (toolState.value.isDrawing && toolState.value.drawingPoints.length > 0) {
      const points = [...toolState.value.drawingPoints, point]
      toolState.value.previewObject = createPreviewObject(points)
    }
  }

  const finishDrawing = () => {
    if (toolState.value.isDrawing) {
      const object = createObjectFromPoints(toolState.value.drawingPoints)
      if (object) {
        // 这里需要将对象添加到设计数据中
        // addObject(object)
        
        // 记录工具历史
        addToolHistory({
          tool: currentTool.value,
          action: 'create',
          object: object,
          timestamp: Date.now()
        })
      }
      
      resetToolState()
    }
  }

  const cancelDrawing = () => {
    resetToolState()
  }

  const setSnapPoints = (points) => {
    toolState.value.snapPoints = points
  }

  const addGuide = (guide) => {
    toolState.value.guides.push(guide)
  }

  const clearGuides = () => {
    toolState.value.guides = []
  }

  const addToolHistory = (entry) => {
    toolHistory.value.push(entry)
    // 限制历史记录数量
    if (toolHistory.value.length > 100) {
      toolHistory.value.shift()
    }
  }

  const getToolHistory = (toolName = null) => {
    if (toolName) {
      return toolHistory.value.filter(entry => entry.tool === toolName)
    }
    return toolHistory.value
  }

  const clearToolHistory = () => {
    toolHistory.value = []
  }

  // 工具特定的对象创建逻辑
  const createPreviewObject = (points) => {
    switch (currentTool.value) {
      case 'wall':
        return createWallPreview(points)
      case 'furniture':
        return createFurniturePreview(points)
      case 'door':
        return createDoorPreview(points)
      case 'window':
        return createWindowPreview(points)
      case 'text':
        return createTextPreview(points)
      case 'circuit':
        return createCircuitPreview(points)
      case 'annotation':
        return createAnnotationPreview(points)
      default:
        return null
    }
  }

  const createObjectFromPoints = (points) => {
    switch (currentTool.value) {
      case 'wall':
        return createWallObject(points)
      case 'furniture':
        return createFurnitureObject(points)
      case 'door':
        return createDoorObject(points)
      case 'window':
        return createWindowObject(points)
      case 'text':
        return createTextObject(points)
      case 'circuit':
        return createCircuitObject(points)
      case 'annotation':
        return createAnnotationObject(points)
      default:
        return null
    }
  }

  // 各种对象的创建函数
  const createWallPreview = (points) => {
    if (points.length < 2) return null
    
    const start = points[0]
    const end = points[points.length - 1]
    const config = toolConfig.value.wall
    
    return {
      type: 'wall',
      x: Math.min(start.x, end.x),
      y: Math.min(start.y, end.y),
      width: Math.abs(end.x - start.x),
      height: config.thickness,
      color: config.color,
      isPreview: true
    }
  }

  const createWallObject = (points) => {
    const preview = createWallPreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  const createFurniturePreview = (points) => {
    if (points.length < 2) return null
    
    const start = points[0]
    const end = points[points.length - 1]
    const config = toolConfig.value.furniture
    
    return {
      type: 'furniture',
      x: Math.min(start.x, end.x),
      y: Math.min(start.y, end.y),
      width: Math.abs(end.x - start.x),
      height: Math.abs(end.y - start.y),
      color: '#3B82F6',
      isPreview: true
    }
  }

  const createFurnitureObject = (points) => {
    const preview = createFurniturePreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  const createDoorPreview = (points) => {
    if (points.length < 2) return null
    
    const start = points[0]
    const end = points[points.length - 1]
    const config = toolConfig.value.door
    
    return {
      type: 'door',
      x: Math.min(start.x, end.x),
      y: Math.min(start.y, end.y),
      width: config.width,
      height: config.height,
      color: '#8B4513',
      isPreview: true
    }
  }

  const createDoorObject = (points) => {
    const preview = createDoorPreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  const createWindowPreview = (points) => {
    if (points.length < 2) return null
    
    const start = points[0]
    const end = points[points.length - 1]
    const config = toolConfig.value.window
    
    return {
      type: 'window',
      x: Math.min(start.x, end.x),
      y: Math.min(start.y, end.y),
      width: config.width,
      height: config.height,
      color: '#87CEEB',
      isPreview: true
    }
  }

  const createWindowObject = (points) => {
    const preview = createWindowPreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  const createTextPreview = (points) => {
    if (points.length < 1) return null
    
    const point = points[0]
    const config = toolConfig.value.text
    
    return {
      type: 'text',
      x: point.x,
      y: point.y,
      text: '示例文字',
      fontSize: config.fontSize,
      fontFamily: config.fontFamily,
      color: config.color,
      isPreview: true
    }
  }

  const createTextObject = (points) => {
    const preview = createTextPreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  const createCircuitPreview = (points) => {
    if (points.length < 2) return null
    
    const start = points[0]
    const end = points[points.length - 1]
    const config = toolConfig.value.circuit
    
    return {
      type: 'circuit',
      x: Math.min(start.x, end.x),
      y: Math.min(start.y, end.y),
      width: Math.abs(end.x - start.x),
      height: Math.abs(end.y - start.y),
      voltage: config.voltage,
      current: config.current,
      color: '#FFD700',
      isPreview: true
    }
  }

  const createCircuitObject = (points) => {
    const preview = createCircuitPreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  const createAnnotationPreview = (points) => {
    if (points.length < 1) return null
    
    const point = points[0]
    const config = toolConfig.value.annotation
    
    return {
      type: 'annotation',
      x: point.x,
      y: point.y,
      text: '标注',
      fontSize: config.fontSize,
      color: config.color,
      isPreview: true
    }
  }

  const createAnnotationObject = (points) => {
    const preview = createAnnotationPreview(points)
    if (!preview) return null
    
    return {
      ...preview,
      id: generateId(),
      isPreview: false
    }
  }

  // 辅助函数
  const generateId = () => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  const reset = () => {
    currentTool.value = 'select'
    resetToolState()
    clearToolHistory()
  }

  return {
    // 状态
    currentTool,
    toolConfig,
    toolState,
    toolHistory,
    
    // 计算属性
    currentToolConfig,
    currentToolName,
    currentToolIcon,
    currentToolCursor,
    isDrawingTool,
    isSelectionTool,
    isMeasurementTool,
    
    // Actions
    setTool,
    setCurrentTool: setTool, // 别名
    getTool,
    getToolConfig,
    updateToolConfig,
    resetToolState,
    startDrawing,
    addDrawingPoint,
    updateDrawingPreview,
    finishDrawing,
    cancelDrawing,
    setSnapPoints,
    addGuide,
    clearGuides,
    addToolHistory,
    getToolHistory,
    clearToolHistory,
    reset
  }
})
